<template>
  <div class="bg-white rounded-lg p-3 w-full">
    <!-- 顶部搜索和操作区 -->
    <div class="flex justify-between items-center mb-4">
      <div class="flex gap-2">
        <el-form :inline="true" :model="searchForm" class="flex items-center gap-2">
          <el-form-item label="姓名 ">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入患者姓名"
              class="w-60"
              clearable
            >
            </el-input>
          </el-form-item>
          <el-form-item label="电话">
            <el-input v-model="searchForm.phone" placeholder="请输入患者电话" class="w-60" clearable>
            </el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="状态" clearable class="w-60">
              <el-option label="待随访" value="pending" />
              <el-option label="已完成" value="completed" />
              <el-option label="已逾期" value="overdue" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button type="success" @click="handleAddPlan">新建随访计划</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 随访计划列表 -->
    <el-table :data="tableData" stripe border v-loading="loading">
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="patientName" label="患者姓名" min-width="100" />
      <el-table-column prop="phone" label="联系电话" min-width="120" />
      <el-table-column prop="diagnosis" label="诊断" min-width="150" show-overflow-tooltip>
        <template #default="{ row }">
          <div class="flex items-center gap-2">
            <el-tag v-for="(diagnosis, index) in row.diagnosis ? row.diagnosis.split('、') : []" :key="index" :type="getDiagnosisTagType(index)" class="!border-2">
              {{ diagnosis }}
            </el-tag>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="nextFollowup" label="下次随访时间" min-width="150" />
      <el-table-column prop="method" label="随访方式" min-width="100">
        <template #default="{ row }">
          <el-tag :type="getMethodTagType(row.method)">{{ row.method }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" min-width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTagType(row.status)">{{ getStatusLabel(row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="200" fixed="right">
        <template #default="{ row }">
          <el-button 
            type="primary" 
            link 
            @click="handleDoFollowup(row)"
            :disabled="row.status === 'completed'"
          >
            执行随访
          </el-button>
          <el-button type="success" link @click="handleEditPlan(row)">
            编辑计划
          </el-button>
          <el-button type="info" link @click="handleAddIssue(row)">
            记录问题
          </el-button>
          <el-button type="warning" link @click="handleFollowupRecord(row)">
            随访记录
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <Pagination
      v-model:page="currentPage"
      v-model:limit="pageSize"
      :total="total"
      @change="handlePageChange"
    />

    <!-- 新建/编辑随访计划对话框 -->
    <Drawer
      v-model="showPlanDialog"
      :title="editingPlan.id ? '编辑随访计划' : '新建随访计划'"
      width="50%"
    >
      <el-form :model="editingPlan" ref="planFormRef" :rules="planRules" label-width="100px">
        <el-form-item label="患者" prop="patientId">
          <el-select
            v-model="editingPlan.patientId"
            filterable
            remote
            placeholder="请输入患者姓名搜索"
            :remote-method="handleSearchPatient"
            :loading="patientSearchLoading"
          >
            <el-option
              v-for="item in patientOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <span>{{ item.name }}</span>
              <span class="text-gray-400 ml-2">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="随访周期" prop="cycle">
          <el-select v-model="editingPlan.cycle" placeholder="请选择随访周期">
            <el-option label="每周" value="weekly" />
            <el-option label="每月" value="monthly" />
            <el-option label="每季度" value="quarterly" />
            <el-option label="每半年" value="half-yearly" />
            <el-option label="每年" value="yearly" />
          </el-select>
        </el-form-item>
        <el-form-item label="随访方式" prop="method">
          <el-select v-model="editingPlan.method" placeholder="请选择随访方式">
            <el-option label="电话" value="phone" />
            <el-option label="短信" value="sms" />
            <el-option label="邮件" value="email" />
            <el-option label="上门" value="visit" />
          </el-select>
        </el-form-item>
        <el-form-item label="下次随访" prop="nextFollowup">
          <el-date-picker
            v-model="editingPlan.nextFollowup"
            type="datetime"
            placeholder="请选择下次随访时间"
          />
        </el-form-item>
        <el-form-item label="随访内容" prop="content">
          <el-input
            v-model="editingPlan.content"
            type="textarea"
            :rows="4"
            placeholder="请输入随访内容"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="editingPlan.remarks"
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
    </Drawer>

    <!-- 执行随访对话框 -->
    <Drawer
      v-model="showFollowupDialog"
      title="执行随访"
      width="50%"
    >
      <el-form :model="followupRecord" ref="followupFormRef" :rules="followupRules" label-width="100px">
        <el-form-item label="随访方式" prop="method">
          <el-select v-model="followupRecord.method" placeholder="请选择随访方式">
            <el-option label="电话" value="phone" />
            <el-option label="短信" value="sms" />
            <el-option label="邮件" value="email" />
            <el-option label="上门" value="visit" />
          </el-select>
        </el-form-item>
        <el-form-item label="随访内容" prop="content">
          <el-input
            v-model="followupRecord.content"
            type="textarea"
            :rows="4"
            placeholder="请输入随访内容"
          />
        </el-form-item>
        <el-form-item label="患者反馈" prop="feedback">
          <el-input
            v-model="followupRecord.feedback"
            type="textarea"
            :rows="3"
            placeholder="请输入患者反馈"
          />
        </el-form-item>
        <el-form-item label="下次随访" prop="nextFollowup">
          <el-date-picker
            v-model="followupRecord.nextFollowup"
            type="datetime"
            placeholder="请选择下次随访时间"
          />
        </el-form-item>
      </el-form>
    </Drawer>

    <!-- 问题记录对话框 -->
    <Drawer
      v-model="showIssueDialog"
      title="记录问题"
      width="40%"
    >
      <el-form :model="issueRecord" ref="issueFormRef" :rules="issueRules" label-width="100px">
        <el-form-item label="问题描述" prop="description">
          <el-input
            v-model="issueRecord.description"
            type="textarea"
            :rows="3"
            placeholder="请输入问题描述"
          />
        </el-form-item>
        <el-form-item label="处理状态" prop="status">
          <el-select v-model="issueRecord.status" placeholder="请选择处理状态">
            <el-option label="待处理" value="pending" />
            <el-option label="处理中" value="processing" />
            <el-option label="已解决" value="resolved" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理方案" prop="solution">
          <el-input
            v-model="issueRecord.solution"
            type="textarea"
            :rows="3"
            placeholder="请输入处理方案"
          />
        </el-form-item>
      </el-form>
    </Drawer>

    <!-- 在 Dialog 组件后添加抽屉组件 -->
    <Drawer
      v-model="showFollowupRecordDrawer"
      direction="rtl"
      size="40%"
      :title="`${currentPatient?.patientName || ''} 的随访记录`"
    >
      <div class="p-3">
        <div class="mb-3 flex items-center justify-between">
          <div class="flex items-center gap-4">
            <div class="text-gray-600">
              <span class="font-medium">联系电话：</span>
              {{ currentPatient?.phone }}
            </div>
            <div class="text-gray-600 flex items-center gap-2">
              <span class="font-medium">诊断：</span>

              <el-tag v-for="(diagnosis, index) in currentPatient?.diagnosis" :key="index" :type="getDiagnosisTagType(index)" class="!border-2">
                {{ diagnosis }}
              </el-tag>
            </div>
          </div>
        </div>

        <el-timeline>
          <el-timeline-item
            v-for="record in currentPatient?.followupRecords"
            :key="record.id"
            :timestamp="record.time"
            :type="record.status === 'completed' ? 'success' : 'primary'"
            :hollow="record.status !== 'completed'"
            :icon="getFollowupIcon(record.method)"
          >
            <div class="bg-white p-4 rounded-lg shadow-sm hover:shadow-md transition-shadow duration-300">
              <div class="flex items-center gap-2 mb-3">
                <el-tag :type="getMethodTagType(record.method)" effect="plain" class="!border-2">
                  {{ record.method }} 随访
                </el-tag>
                <span class="text-gray-500 text-sm">|</span>
                <span class="text-gray-600">
                  随访人：<span class="font-medium">{{ record.staff }}</span>
                </span>
              </div>
              
              <div class="bg-gray-50 p-3 rounded-lg mb-3">
                <div class="text-gray-900">{{ record.content }}</div>
              </div>

              <div v-if="record.feedback" class="mb-3">
                <div class="flex items-center gap-2 text-gray-500 mb-2">
                  <el-icon><ChatLineRound /></el-icon>
                  <span>患者反馈</span>
                </div>
                <div class="bg-blue-50 p-3 rounded-lg text-gray-700">
                  {{ record.feedback }}
                </div>
              </div>

              <div v-if="record.issues && record.issues.length" class="mt-4">
                <div class="flex items-center gap-2 text-gray-500 mb-3">
                  <el-icon><Warning /></el-icon>
                  <span>问题跟踪</span>
                </div>
                <el-steps 
                  :active="getIssueActiveStep(record.issues)" 
                  simple 
                  class="issue-steps"
                >
                  <el-step 
                    v-for="issue in record.issues" 
                    :key="issue.id"
                    :title="getIssueStatusLabel(issue.status)"
                    :icon="getIssueStatusIcon(issue.status)"
                  >
                    <template #description>
                      <div class="py-1">{{ issue.description }}</div>
                      <div v-if="issue.solution" class="text-gray-500 text-sm mt-1">
                        解决方案：{{ issue.solution }}
                      </div>
                    </template>
                  </el-step>
                </el-steps>
              </div>
            </div>
          </el-timeline-item>
        </el-timeline>

        <div v-if="!currentPatient?.followupRecords?.length" class="text-center text-gray-500 py-8">
          暂无随访记录
        </div>
      </div>
    </Drawer>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { Search, ChatLineRound, Warning, Phone, Message, House, Document, CircleCheck, Loading, More } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import Pagination from '@/components/common/pagination.vue'
import Drawer from '@/components/common/Drawer.vue'

// 搜索表单
const searchForm = ref({
  keyword: '',
  status: ''
})

// 表格加载状态
const loading = ref(false)

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 表格数据
const tableData = ref([
  {
    id: 1,
    patientName: '张三',
    phone: '13800138000',
    diagnosis: '高血压、糖尿病',
    nextFollowup: '2024-02-01 10:00',
    method: 'phone',
    status: 'pending',
    followupRecords: [
      {
        id: 1,
        time: '2024-01-15 09:30',
        method: '电话',
        staff: '李医生',
        content: '询问患者血压情况和服药情况',
        feedback: '血压稳定，按时服药',
        status: 'completed',
        issues: [
          {
            id: 1,
            description: '患者反映偶有头晕',
            status: '已解决',
            solution: '调整用药剂量'
          }
        ]
      }
    ]
  }
])

// 获取随访方式标签类型
const getMethodTagType = (method) => {
  const types = {
    phone: '',
    sms: 'success',
    email: 'warning',
    visit: 'danger'
  }
  return types[method] || 'info'
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const types = {
    pending: 'warning',
    completed: 'success',
    overdue: 'danger'
  }
  return types[status] || 'info'
}

// 获取状态标签文本
const getStatusLabel = (status) => {
  const labels = {
    pending: '待随访',
    completed: '已完成',
    overdue: '已逾期'
  }
  return labels[status] || status
}

// 获取问题处理进度
const getIssueActiveStep = (issues) => {
  const lastIssue = issues[issues.length - 1]
  const steps = {
    pending: 1,
    processing: 2,
    resolved: 3
  }
  return steps[lastIssue.status] || 1
}

// 新建/编辑随访计划
const showPlanDialog = ref(false)
const planFormRef = ref()
const editingPlan = ref({
  patientId: '',
  cycle: '',
  method: '',
  nextFollowup: '',
  content: '',
  remarks: ''
})

// 随访计划表单验证规则
const planRules = {
  patientId: [{ required: true, message: '请选择患者', trigger: 'change' }],
  cycle: [{ required: true, message: '请选择随访周期', trigger: 'change' }],
  method: [{ required: true, message: '请选择随访方式', trigger: 'change' }],
  nextFollowup: [{ required: true, message: '请选择下次随访时间', trigger: 'change' }],
  content: [{ required: true, message: '请输入随访内容', trigger: 'blur' }]
}

// 患者搜索
const patientSearchLoading = ref(false)
const patientOptions = ref([])
const handleSearchPatient = async (query) => {
  if (query) {
    patientSearchLoading.value = true
    // 这里调用后端接口搜索患者
    await new Promise(resolve => setTimeout(resolve, 1000))
    patientOptions.value = [
      { id: 1, name: '张三', phone: '13800138000' },
      { id: 2, name: '李四', phone: '13900139000' }
    ]
    patientSearchLoading.value = false
  }
}

// 执行随访
const showFollowupDialog = ref(false)
const followupFormRef = ref()
const followupRecord = ref({
  method: '',
  content: '',
  feedback: '',
  nextFollowup: ''
})

// 随访记录表单验证规则
const followupRules = {
  method: [{ required: true, message: '请选择随访方式', trigger: 'change' }],
  content: [{ required: true, message: '请输入随访内容', trigger: 'blur' }],
  nextFollowup: [{ required: true, message: '请选择下次随访时间', trigger: 'change' }]
}

// 问题记录
const showIssueDialog = ref(false)
const issueFormRef = ref()
const issueRecord = ref({
  description: '',
  status: 'pending',
  solution: ''
})

// 问题记录表单验证规则
const issueRules = {
  description: [{ required: true, message: '请输入问题描述', trigger: 'blur' }],
  status: [{ required: true, message: '请选择处理状态', trigger: 'change' }]
}

// 搜索
const handleSearch = () => {
  // 这里调用后端接口进行搜索
  console.log('搜索条件：', searchForm.value)
}

// 新建随访计划
const handleAddPlan = () => {
  editingPlan.value = {
    patientId: '',
    cycle: '',
    method: '',
    nextFollowup: '',
    content: '',
    remarks: ''
  }
  showPlanDialog.value = true
}

// 编辑随访计划
const handleEditPlan = (row) => {
  editingPlan.value = { ...row }
  showPlanDialog.value = true
}

// 执行随访
const handleDoFollowup = (row) => {
  followupRecord.value = {
    method: row.method,
    content: '',
    feedback: '',
    nextFollowup: ''
  }
  showFollowupDialog.value = true
}

// 记录问题
const handleAddIssue = (row) => {
  issueRecord.value = {
    description: '',
    status: 'pending',
    solution: ''
  }
  showIssueDialog.value = true
}

// 处理分页变化
const handlePageChange = ({ page, limit }) => {
  currentPage.value = page
  pageSize.value = limit
  // 重新加载数据
}

// 在 script setup 部分添加以下内容
const getFollowupIcon = (method) => {
  const icons = {
    phone: 'Phone',
    sms: 'Message',
    email: 'Message',
    visit: 'House'
  }
  return icons[method] || 'Document'
}

const getIssueStatusLabel = (status) => {
  const labels = {
    pending: '待处理',
    processing: '处理中',
    resolved: '已解决'
  }
  return labels[status] || status
}

const getIssueStatusIcon = (status) => {
  const icons = {
    pending: 'Warning',
    processing: 'Loading',
    resolved: 'CircleCheck'
  }
  return icons[status] || 'More'
}

// 随访记录
const showFollowupRecordDrawer = ref(false)
const currentPatient = ref(null)

const handleFollowupRecord = (row) => {
  // 如果 diagnosis 是字符串，将其转换为数组
  const diagnosisList = row.diagnosis ? row.diagnosis.split('、') : []
  currentPatient.value = {
    ...row,
    diagnosis: diagnosisList
  }
  showFollowupRecordDrawer.value = true
}

// 获取诊断标签类型
const getDiagnosisTagType = (index) => {
  const tagType = ref(['info', 'danger', 'warning', 'primary', 'success'])
  return tagType.value[index]
}


</script>

<style scoped>
.el-table :deep(.el-table__expanded-cell) {
  padding: 1rem;
}

:deep(.issue-steps) {
  .el-step__title {
    font-size: 14px;
  }
  .el-step__description {
    font-size: 13px;
  }
  .el-step.is-success .el-step__title,
  .el-step.is-success .el-step__description {
    color: var(--el-color-success);
  }
  .el-step.is-process .el-step__title,
  .el-step.is-process .el-step__description {
    color: var(--el-color-primary);
  }
}
</style>

